package SDK;

import java.io.*;
import java.net.HttpURLConnection;

public class Upload {
    public static String uploadFile(String uploadFilePath){
        HttpURLConnection connection = HttpUtil.creatUrl("http://127.0.0.1:8080/file/upload", "POST");
        //首先判断文件是否存在
        File file = new File(uploadFilePath);
        if (!file.exists()){
            return "文件不存在，上传失败";
        }
        //文件类型
        String type=uploadFilePath.substring(uploadFilePath.indexOf(".")+1);
        //将必要信息传给服务端
        connection.setRequestProperty("size", String.valueOf(file.length()));
        connection.setRequestProperty("type",type);
        connection.setRequestProperty("oldName", file.getName());
        try {
            //将文件写入缓冲区
            OutputStream os=new DataOutputStream(connection.getOutputStream());
            FileInputStream fis=new FileInputStream(uploadFilePath);
            byte[] buffer=new byte[1024];
            int length=-1;
            while ((length=fis.read(buffer))!=-1){
                os.write(buffer,0,length);
            }
            fis.close();
            os.flush();
            InputStream is=connection.getInputStream();
            is.close();
            os.close();
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
    }
}
